﻿IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_CreateOrUpdateJPushMessageLog]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_CreateOrUpdateJPushMessageLog]
GO

CREATE PROCEDURE [dbo].[sp_CreateOrUpdateJPushMessageLog](
    @MessageId INT,
    @ReceiverValue NVARCHAR(MAX),
    @Content NVARCHAR(MAX),
    @Platform INT,
    @CustomizedValue XML,
    @MessageType INT,
    @PushType INT,
    @ResponseCode INT,
    @ResponseMessage NVARCHAR(MAX),
    @PushTitle NVARCHAR(MAX),
    @BuilderId NVARCHAR(MAX),
    @AndroidDeliveredCount INT,
    @ApplePushNotificationDeliveredCount INT,
    @IsTest BIT
)
AS

BEGIN
    DECLARE @Key AS UNIQUEIDENTIFIER;
    DECLARE @NowTime AS DATETIME = GETUTCDATE();

    IF @MessageId IS NOT NULL
    BEGIN

        SELECT @Key = [Key]
            FROM [dbo].[JPushMessageLog]
            WHERE [MessageId] = @MessageId;

        IF @Key IS NULL
        BEGIN
            SET @Key = NEWID();

             INSERT INTO [dbo].[JPushMessageLog]
               ([Key]
               ,[MessageId]
               ,[ReceiverValue]
               ,[Content]
               ,[Platform]
               ,[CustomizedValue]
               ,[MessageType]
               ,[PushType]
               ,[ResponseCode]
               ,[ResponseMessage]
               ,[PushTitle]
               ,[BuilderId]
               ,[AndroidDeliveredCount]
               ,[ApplePushNotificationDeliveredCount]
               ,[IsTest]
               ,[CreatedStamp]
               ,[LastUpdatedStamp])
               VALUES(
                @Key,
                @MessageId,
                @ReceiverValue,
                @Content,
                @Platform,
                @CustomizedValue,
                @MessageType,
                @PushType,
                @ResponseCode,
                @ResponseMessage,
                @PushTitle,
                @BuilderId,
                @AndroidDeliveredCount,
                @ApplePushNotificationDeliveredCount,
                @IsTest,
                @NowTime,
                @NowTime
               );
        END
        ELSE
        BEGIN
            UPDATE [dbo].[JPushMessageLog]
                SET [ApplePushNotificationDeliveredCount] = @ApplePushNotificationDeliveredCount,
                    [AndroidDeliveredCount] = @AndroidDeliveredCount,
                    [LastUpdatedStamp] = @NowTime
                WHERE [Key] = @Key;
        END
    END 
END
GO